package com.tencreat.common.core.security.config;

import com.tencreat.common.core.security.filter.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;

@Configuration
public class WebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Autowired
    JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Autowired
    AuthenticationFailureHandler authenticationFailureHandler;

    @Autowired
    private CorsFilter corsFilter;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        // 认证失败处理
        httpSecurity.exceptionHandling().authenticationEntryPoint(authenticationFailureHandler);
        // 在 UsernamePasswordAuthenticationFilter 之前添加 JWT 拦截器
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        // CORS
        httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class);
        // 配置 session 策略为无状态，即不创建 session
        httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        // 禁用 CSRF 保护（在使用 token 时通常不需要）
        httpSecurity.csrf().disable();

        httpSecurity.authorizeRequests()
                .antMatchers("/admin/**").hasAuthority("admin")
                .antMatchers("/api/account/login").permitAll()
                .antMatchers("/open/**").permitAll()
                .antMatchers("/test/**").permitAll()
                .anyRequest().authenticated();

    }

}